<template>
  <div class="patrol-point-container">
    <div class="search-bar">
      <div class="search-section">
        <div class="search-inputs">
          <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            class="search-item"
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-select
            v-model="queryParams.buildingId"
            placeholder="请选择楼宇"
            clearable
            class="search-item"
          >
            <el-option
              v-for="item in buildingOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-input
            v-model="queryParams.searchText"
            placeholder="请输入巡更点名称"
            class="search-item search-input"
            @keyup.enter.native="searchData"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchData"
            ></el-button>
          </el-input>
          <div class="search-buttons">
            <el-button
              type="info"
              plain
              icon="el-icon-refresh"
              @click="resetSearch"
              >重置</el-button
            >
            <el-button type="primary" icon="el-icon-search" @click="searchData"
              >搜索</el-button
            >
          </div>
        </div>
      </div>
      <div class="add-section">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          class="add-button"
          >添加巡更点</el-button
        >
      </div>
    </div>

    <div class="table-container">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80" fixed>
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column
          prop="communityName"
          label="所属小区"
          width="130"
        ></el-table-column>
        <el-table-column
          prop="buildingName"
          label="楼宇名称"
          width="240"
        ></el-table-column>
        <el-table-column
          prop="categoryName"
          label="巡更类别"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="pointName"
          label="巡更点名称"
          width="152"
        ></el-table-column>
        <el-table-column
          prop="locationCode"
          label="位置编号"
          width="105"
        ></el-table-column>
        <el-table-column
          prop="photoRequired"
          label="拍照要求"
          width="135"
          align="center"
        >
          <template slot-scope="scope">
            <span
              :class="
                scope.row.photoRequired === 1
                  ? 'photo-required'
                  : 'photo-not-required'
              "
            >
              {{ scope.row.photoRequired === 1 ? "要求拍照" : "无要求" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <span
              :class="
                scope.row.status === 1 ? 'status-normal' : 'status-abnormal'
              "
            >
              {{ scope.row.status === 1 ? "启用" : "禁用" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              plain
              @click="handleView(scope.row)"
              >巡更记录</el-button
            >
            <el-button
              type="warning"
              size="mini"
              plain
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              plain
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      queryParams: {
        communityId: null,
        buildingId: null,
        searchText: "",
        pageNum: 1,
        pageSize: 10,
      },
      communityOptions: [], // 社区选项，需要从后端获取
      buildingOptions: [], // 楼宇选项，需要从后端获取
      tableData: [],
      total: 0,
      loading: false,
      form: {
        area: "",
        unit: "",
        floor: "",
        region: "",
        patrolId: "",
        department: "",
        status: "正常",
      },
      rules: {
        area: [{ required: true, message: "请输入房屋/区", trigger: "blur" }],
        unit: [{ required: true, message: "请输入相对单元", trigger: "blur" }],
        floor: [{ required: true, message: "请输入楼层", trigger: "blur" }],
        region: [
          { required: true, message: "请输入区域的将", trigger: "blur" },
        ],
        patrolId: [
          { required: true, message: "请输入巡检编号", trigger: "blur" },
        ],
        department: [
          { required: true, message: "请输入巡检部门", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      currentRow: null,
    };
  },

  created() {
    this.loadCommunityOptions();
    this.fetchData();
  },

  methods: {
    // 加载社区选项
    loadCommunityOptions() {
      // 可以从API获取社区列表
      this.$axios
        .get("api/infrastructure-server/community/queryAll")
        .then((response) => {
          if (response.data && response.data.code === 200) {
            this.communityOptions = response.data.data.map((item) => {
              return { value: item.id, label: item.name };
            });
          }
        })
        .catch((error) => {
          console.error("获取社区列表错误:", error);
        });
    },

    // 根据社区ID加载楼宇选项
    loadBuildingOptions(communityId) {
      if (!communityId) {
        this.buildingOptions = [];
        this.queryParams.buildingId = null;
        return;
      }

      this.$axios
        .get(`api/infrastructure-server/building/queryById/${communityId}`)
        .then((response) => {
          if (response.data && response.data.code === 200) {
            this.buildingOptions = response.data.data.map((item) => {
              return { value: item.id, label: item.name };
            });
          }
        })
        .catch((error) => {
          console.error("获取楼宇列表错误:", error);
        });
    },

    // 获取数据
    fetchData() {
      this.loading = true;

      // 调用后端API
      this.$axios
        .post("api/patrol-server/patrol/queryByPageInfo", this.queryParams)
        .then((response) => {
          if (response.data && response.data.code === 200) {
            const data = response.data.data;
            this.tableData = data.records.map((item) => ({
              ...item,
              pointId: String(item.pointId), // 转换为字符串防止精度丢失
            }));

            // 如果total为0但records有数据，使用records长度作为total
            this.total = data.total || (data.records ? data.records.length : 0);
          } else {
            this.$message.error("获取巡更点数据失败");
          }
        })
        .catch((error) => {
          console.error("获取巡更点数据错误:", error);
          this.$message.error("获取巡更点数据出错");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 搜索
    searchData() {
      this.queryParams.pageNum = 1; // 搜索时重置为第一页
      this.fetchData();
    },

    // 重置搜索
    resetSearch() {
      this.queryParams = {
        communityId: null,
        buildingId: null,
        searchText: "",
        pageNum: 1,
        pageSize: this.queryParams.pageSize,
      };
      this.fetchData();
    },

    // 监听社区变化，加载对应的楼宇
    handleCommunityChange(communityId) {
      this.loadBuildingOptions(communityId);
    },

    // 添加巡更点
    handleAdd() {
      this.$router.push({
        path: "patrolPointAdd",
      });
    },

    // 查看巡更点
    handleView(row) {
      this.$router.push({
        path: "patrolPointRecordDisplay",
        query: { patrolPointId: row.pointId },
      });
    },

    // 编辑巡更点
    handleEdit(row) {
        this.$router.push({
        path: "patrolPointUpdate",
        query: { patrolPointId: row.pointId },
      });
    },

    // 删除巡更点
    handleDelete(row) {
      this.$confirm("确认删除该巡更点?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          // 实际删除API调用
          this.$axios
            .get(`api/patrol-server/patrol/delete/${String(row.pointId)}`)
            .then((response) => {
              if (response.data && response.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.fetchData();
              } else {
                this.$message.error(response.data.msg || "删除失败");
              }
            })
            .catch((error) => {
              console.error("删除巡更点错误:", error);
              this.$message.error("删除失败，请稍后重试");
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 分页相关
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.fetchData();
    },

    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.fetchData();
    },
  },
};
</script>

<style scoped>
.patrol-point-container {
  padding: 25px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 120px);
}

.search-bar {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-section {
  margin-bottom: 15px;
}

.search-inputs {
  display: flex;
  flex-wrap: nowrap;
  gap: 15px;
  align-items: center;
}

.search-item {
  min-width: 180px;
  flex-grow: 1;
}

.search-input {
  min-width: 280px;
  flex-grow: 2;
}

.search-buttons {
  display: flex;
  gap: 10px;
  white-space: nowrap;
}

.add-section {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
  margin-top: 5px;
}

.add-button {
  height: 40px;
  padding: 0 30px;
}

.table-container {
  background-color: #fff;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 18px 0 rgba(0, 0, 0, 0.08);
  margin-top: 20px;
}

.pagination {
  margin-top: 25px;
  text-align: right;
  padding: 10px 0;
}

.status-normal {
  color: #67c23a;
  font-weight: 500;
  padding: 2px 10px;
  background-color: rgba(103, 194, 58, 0.1);
  border-radius: 12px;
}

.status-abnormal {
  color: #f56c6c;
  font-weight: 500;
  padding: 2px 10px;
  background-color: rgba(245, 108, 108, 0.1);
  border-radius: 12px;
}

.photo-required {
  color: #409eff;
  font-weight: 500;
  padding: 2px 10px;
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 12px;
}

.photo-not-required {
  color: #909399;
  font-weight: 500;
  padding: 2px 10px;
  background-color: rgba(144, 147, 153, 0.1);
  border-radius: 12px;
}
</style>
